package com.dyson.client.jedis;

import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * @author:Dyson
 * @time:2019/9/26 15:57
 */
public class JClient {
    public static void main(String[] args) {
        //通过ip及端口连接redis
        Jedis jedis = new Jedis("192.168.237.128", 6379);
        //如果未设置密码,可省略
        jedis.auth("root");
        //ping redis服务,  返回值PONG,即成功
        System.out.println(jedis.ping());
        /*jedis API 与redis命令保持一致,按照命令方式调用即可*/
        /*String基本操作*/
        //1.存取
        jedis.set("sk1", "sv1");
        System.out.println(jedis.get("sk1"));
        //存在不设置,存在设置
        jedis.setnx("ska", "sva");
        //2.自增自减,返回值为修改后实际存储的值
        //依次++,--
        System.out.println(jedis.incr("sk2"));
        System.out.println(jedis.decr("sk2"));
        //依次+步长,-步长
        System.out.println(jedis.incrBy("sk3", 3));
        System.out.println(jedis.decrBy("sk3", 3));
        //3.过期时间
        //设置数据时设置,这里设置5秒过期
        jedis.setex("sk4", 5, "sv4");
        System.out.println(jedis.get("sk4"));
        try {
            //休眠5秒
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //key已被清理, redis空返回nil, jedis转为null
        System.out.println(jedis.get("sk4"));
        //获取key过期时间,不过期返回-1, key不存在返回-2
        System.out.println(jedis.ttl("sk4"));
        //单独设置失效时间
        jedis.set("sk5", "sv5");
        System.out.println(jedis.expire("sk5", 5));
        System.out.println(jedis.ttl("sk5"));
        //取当前db所有key
        Set<String> keys = jedis.keys("*");
        keys.forEach(key -> System.out.println(key));
        //检查key是否存在
        System.out.println(jedis.exists("k1"));
        //key ,db之间移动
        System.out.println(jedis.move("k1", 2));
        //key值数据类型
        System.out.println(jedis.type("k1"));
        //关闭连接
        jedis.close();
    }
}
